package com.github.boluo1230.wechat.service.mp.impl;

import com.github.boluo1230.wechat.dao.WxUserDao;
import com.github.boluo1230.wechat.entity.MpApp;
import com.github.boluo1230.wechat.entity.WxUser;
import com.github.boluo1230.wechat.feign.WxAPI;
import com.github.boluo1230.wechat.service.mp.RedisService;
import com.github.boluo1230.wechat.service.mp.WxUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Code Farmer
 * @date 2019/10/14 14:48
 */
@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    private WxUserDao wxUserDao;
    @Autowired
    private RedisService redisService;
    @Autowired
    private WxAPI wxAPI;

    @Override
    public WxUser recordUserInfo(MpApp mpApp, String openId, String event) {
        String appId = mpApp.getAppId();
        if (StringUtils.isNotBlank(event) && event.equals("unsubscribe")) {
            wxUserDao.unSubscribe(openId, mpApp.getAppId());
        } else {
            WxUser wxUser = redisService.getWxUser(appId, openId);
            if (wxUser == null) {
                wxUser = wxAPI.getWxUser(openId, mpApp.getTokenUrl());
                redisService.setWxUser(mpApp.getAppId(), openId, wxUser);
            }
            wxUserDao.insert(wxUser, mpApp.getAppId());
            return wxUser;
        }
        return null;
    }
}
